import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleTelnet {
    public static void main(String[] args) throws IOException {
        String hostName;
        int portNumber;

        if (args.length != 2) {
            System.err.println("Usage: java SimpleTelnet <host name> <port number>");
            System.exit(1);
        }

        hostName = args[0];
        portNumber = Integer.parseInt(args[1]);

        try ( Socket socket = new Socket(hostName, portNumber);
              PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
              BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            String command;

            System.out.println("< Telnet Prompt >");
            do
            {
                command = br.readLine();
                if(!command.equals("disconnect"))
                {
                    out.println(command);
                    System.out.println(in.readLine());
                }
            }while( !command.equals("disconnect") );
            socket.close();
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " + hostName);
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
